from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.exc import IntegrityError
from sqlalchemy.orm import Session
from database import get_db
from schemas.pharmacist_schemas import PharmacistCreate, PharmacistUpdate
from services.auth_service import require_user

from config import *  # 导入所有配置
from models.user_models import *

from services.user_service import get_all_users,get_user,create_user,delete_user,update_user

router = APIRouter()

# 查询获取所有药剂师信息
@router.get("/pharmacists")
def get_pharmacists(db: Session = Depends(get_db),
                    user=Depends(require_user(UserType.ADMIN, UserType.PHARMACIST))):
    return get_all_users(UserType.PHARMACIST, db)

# 查询单个药剂师的信息
@router.get("/pharmacists/{pharmacists_id}")
def get_pharmacist(pharmacists_id:int,db: Session = Depends(get_db),user=Depends(require_user(UserType.ADMIN,UserType.PHARMACIST))):
    return get_user(UserType.PHARMACIST,db,pharmacists_id)


# 创建药剂师账户
@router.post("/pharmacists")
def create_pharmacist(pharmacist: PharmacistCreate,
                      db: Session = Depends(get_db),
                      user=Depends(require_user(UserType.ADMIN))):
    return create_user(UserType.PHARMACIST, db, pharmacist)


# 删除药剂师账户
@router.delete("/pharmacists/{pharmacist_id}")
def delete_pharmacist(pharmacist_id: int,
                      db: Session = Depends(get_db),
                      user=Depends(require_user(UserType.ADMIN))):
    return delete_user(UserType.PHARMACIST,db,pharmacist_id)


# 更新药剂师信息
@router.put("/pharmacists/{pharmacist_id}")
def update_pharmacist(pharmacist_id: int,
                      pharmacist_update: PharmacistUpdate,
                      db: Session = Depends(get_db),
                      user=Depends(require_user(UserType.ADMIN,UserType.PHARMACIST))):
    if user["user_type"] == 'PHARMACIST' and user['user_ref_id'] != pharmacist_id:
        raise HTTPException(
            status_code=403,
            detail=f"PHARMACIST with ID {user['user_ref_id']} is not allowed to update patient {pharmacist_id}."
        )
    return update_user(UserType.PHARMACIST, db, pharmacist_update, pharmacist_id)